package work;

import java.util.LinkedList;
import java.util.Queue;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static TreeNode createTree(Integer[] treeArr) {
        Queue<TreeNode> queue = new LinkedList<>();
        int length = treeArr.length;
        int index = 0;
        //初始化，创建根节点，进队
        Integer rootValue = treeArr[index++];
        TreeNode root = new TreeNode(rootValue);
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            TreeNode left = null;
            if(index<length) {//若数组数组还有元素，创建子树入队
                Integer leftNum = treeArr[index++];
                if(leftNum!=null) {//数组元素不能为null
                    left = new TreeNode(leftNum);
                    queue.offer(left);
                }
            }
            TreeNode right = null;
            if(index<length) {
                Integer rightNum = treeArr[index++];
                if(rightNum!=null) {//数组元素不能为null
                    right = new TreeNode(rightNum);
                    queue.offer(right);
                }
            }

            //将左右子节点的父亲设置为node节点
            node.left = left;
            node.right = right;

        }

        return root;
    }
}